import datetime

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.filters import OrderingFilter

from .filters import UserFilter
from .models import UserModel
from .serializers import UserSerializer
from icdemoapi.utils.paging import LargeResultsSetPagination


class UserView(ListAPIView):
    """用户视图"""
    queryset = UserModel.objects.all()
    serializer_class = UserSerializer
    filter_class = UserFilter  # 过滤
    filter_backends = [DjangoFilterBackend, OrderingFilter]  # 排序
    ordering_fields = ('id', 'user_name', 'full_name', 'update_datetime')  # 参与排序的字段
    pagination_class = LargeResultsSetPagination  # 分页

    def get(self, request, *args, **kwargs):
        """获取数据"""
        return self.list(request, *args, **kwargs)

    def post(self, request):
        """添加数据"""
        data = request.data
        if not data.get('deleted'):
            data['deleted'] = False
        if not data.get('is_active'):
            data['is_active'] = True
        if not data.get('create_datetime'):
            data['create_datetime'] = datetime.datetime.now()
        if not data.get('update_datetime'):
            data['update_datetime'] = datetime.datetime.now()
        if not data.get('login_fail_num'):
            data['login_fail_num'] = 0

        serializer = UserSerializer(data=data)

        if not serializer.is_valid():
            return Response(serializer.errors)
        else:
            serializer.save()
            return Response(serializer.data, status=201)


class UserDetailView(APIView):
    """带主键url"""

    def get(self, request, id):
        product = UserModel.objects.get(pk=id)
        serializer = UserSerializer(instance=product, many=False)
        return Response(serializer.data)

    def put(self, request, id):
        old_data = UserModel.objects.get(pk=id)
        new_data = request.data
        if not new_data.get('login_fail_num'):
            new_data['login_fail_num'] = 0
        new_data['update_datetime'] = datetime.datetime.now()
        serializer = UserSerializer(instance=old_data, data=new_data)
        if not serializer.is_valid():
            return Response(serializer.errors)
        else:
            serializer.save()
            return Response(serializer.data)

    def delete(self, request, id):
        product = UserModel.objects.get(pk=id)
        product.delete()
        return Response(status=204)
